<?php
require_once __DIR__ . '/../common/functions.php';
checkLogin();
global $pdo;

$action = $_REQUEST['action'] ?? '';
try {
    switch ($action) {
        // 新增分类
        case 'add':
            $name = trim($_POST['name'] ?? '');
            $sort = intval($_POST['sort'] ?? 0);
            if (empty($name)) error('分类名称不能为空');
            $stmt = $pdo->prepare("INSERT INTO article_category (name, sort) VALUES (?, ?)");
            $stmt->execute([$name, $sort]);
            success([], '新增分类成功');
            break;

        // 编辑分类
        case 'edit':
            $id = intval($_POST['id'] ?? 0);
            $name = trim($_POST['name'] ?? '');
            $sort = intval($_POST['sort'] ?? 0);
            if ($id <= 0 || empty($name)) error('参数错误');
            $stmt = $pdo->prepare("UPDATE article_category SET name=?, sort=? WHERE id=?");
            $stmt->execute([$name, $sort, $id]);
            success([], '编辑成功');
            break;

        // 删除分类
        case 'delete':
            $id = intval($_POST['id'] ?? 0);
            if ($id <= 0) error('无效ID');
            // 先将关联文章的分类ID设为0（未分类）
            $pdo->prepare("UPDATE article SET category_id=0 WHERE category_id=?")->execute([$id]);
            // 再删除分类
            $stmt = $pdo->prepare("DELETE FROM article_category WHERE id=?");
            $stmt->execute([$id]);
            success([], '删除成功');
            break;

        default:
            error('无效操作');
    }
} catch (PDOException $e) {
    error('操作失败：' . $e->getMessage());
}